//
//  LJPhotoBrowserController.swift
//  LJWeibo
//
//  Created by Raymond on 16/1/4.
//  Copyright © 2016年 liu. All rights reserved.
//

import UIKit

class LJPhotoBrowserController: UIViewController {

    /// 选中的indexpath
    private var selectedIndexPath: NSIndexPath
    
    /// 大图的URL数组
    private var URLs: [NSURL]
    
    /// collectionView布局对象
    private let layout = UICollectionViewFlowLayout()
    
    /// cell重用标示
    private let ReuseIdentifier = "ReuseIdentifier"
    
    /// cell间距
    private let cellMargin: CGFloat = 10
    
    init(indexPath: NSIndexPath, URLs: [NSURL]) {
        self.selectedIndexPath = indexPath
        self.URLs = URLs
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
//        pageLabel.text = "5/9"
    }
    // 该方法中将collection滚动值
    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        setPageNum(selectedIndexPath.item)
    }
    
    // 准备UI
    private func prepareUI() {
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 如果collectioView使用autoLayout约束的是滚不动的,改成frame来设置宽高
        // 将collectionView大小加上间距，这样每次拖动时会拖动屏幕的宽度加上cell的间距
        collectionView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width + cellMargin, height: UIScreen.mainScreen().bounds.height)
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb": closeButton]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sb": saveButton]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb": closeButton, "sb": saveButton]))
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        // 注册cell
        collectionView.registerClass(LJPhotoBroserCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        // 设置itemsize
        layout.itemSize = UIScreen.mainScreen().bounds.size
        // 设置间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        // 设置滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 隐藏滚动条
        collectionView.showsHorizontalScrollIndicator = false
        // 设置分页
        collectionView.pagingEnabled = true
        // 取消弹簧
        collectionView.bounces = false
        // 向右缩进，避免最后一张图无法完全显示
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: cellMargin)
        // 指定代理
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    /// 设置页码的方法
    private func setPageNum(num: Int) {
        pageLabel.text = "\(num+1)/\(URLs.count)"
    }
    
    // MARK: - 按钮点击事件
    /// 关闭按钮被点击
    @objc private func closeButtonDidClick() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    /// 保存按钮被点击
    @objc private func saveButtonDidClick() {
        print("save")
    }
    
    //MARK: - 懒加载
    /// 图片
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.setTitle("关闭", forState: UIControlState.Normal)
        button.addTarget(self, action: "closeButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    /// 保存按钮
    private lazy var saveButton: UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.setTitle("保存", forState: UIControlState.Normal)
        button.addTarget(self, action: "saveButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    /// 页码标示
    private lazy var pageLabel: UILabel = UILabel(textColor: UIColor.whiteColor(), fontSize: 13)
}

extension LJPhotoBrowserController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return URLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! LJPhotoBroserCell
        cell.backgroundColor = UIColor.randomColor()
        cell.imageURL = URLs[indexPath.item]
        return cell
    }
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取正在显示indexpath
//        let indexPath = collectionView.indexPathsForVisibleItems().first!
        let offsetX = collectionView.contentOffset.x
        let num = Int(offsetX) / Int(UIScreen.mainScreen().bounds.width)
        setPageNum(num)
    }
}
